package com.yunfei.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownloadPdf {

    /**
     * 从网络Url中下载文件
     * @param urlStr
     * @param fileName
     * @param savePath
     * @throws IOException
     */
    public static void  downLoadByUrl(String urlStr,String fileName,String savePath) throws IOException{
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(5*1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        //得到输入流
        InputStream inputStream = conn.getInputStream();
        //获取自己数组
        byte[] getData = readInputStream(inputStream);
        //文件保存位置
        File saveDir = new File(savePath);
        if(!saveDir.exists()){
            saveDir.mkdir();
        }
        File file = new File(saveDir+File.separator+fileName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getData);
        if(fos!=null){
            fos.close();
        }
        if(inputStream!=null){
            inputStream.close();
        }
        System.out.println("info:"+url+" download success"+saveDir+File.separator+fileName);

    }


    /**
     * 从输入流中获取字节数组
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static  byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }
    /**
    * @Description: 下载远程服务器文件到本地服务器
     * @param url 远程服务器在线访问笛子
     * @param  localFileName 生成本地服务器的文件名称
     * @param localFilePath 生成本地服务器的文件存放路径
     * @return flag 判断文件是否存在
    * @Author: zhengyunfei
    * @Date: 2018/12/28
    * @time:16:39
    */
    public static boolean downLoadServerFileToLocal(String url,String localFileName,String localFilePath){
        boolean flag=true;
        try{
            File file=new File(localFilePath+"/"+localFileName);
            System.out.println("保存文件="+localFilePath+"/"+localFileName);
            //判断父目录是否存在，如果不存在，则创建
            if (file.getParentFile() != null && !file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            if(!file.exists()){
                downLoadByUrl(url,localFileName,localFilePath);
            }else{
                flag=false;//文件已存在
            }
        }catch (Exception e){
            //e.printStackTrace();
            flag=false;
            System.out.println("未找到原始文件:"+url);
        }
        return flag;
    }
    public static void main(String[] args) {
        try{
            String url="http://10.0.190.7:8763/files/2018-08-13/Tblobstorage/624/6244baccessory";
            String filename="a.pdf";
            String filePath="D:/log/";
            int index = url.lastIndexOf("/");
          //  url = url.substring(0, index) + "/" + URLEncoder.encode(filename,"utf-8");
            File file=new File(filePath+filename);
            if(!file.exists()){
                downLoadByUrl(url,
                        filename,filePath);
            }

        }catch (Exception e) {
            // TODO: handle exception
        }
    }
}